package com.ruoyi.finance.test;

import redis.clients.jedis.Jedis;

import java.util.Random;

public class CacheAvalancheSimulation {
    private static final int CACHE_SIZE = 100;
    private static final int EXPIRE_TIME = 60; // 缓存过期时间，单位：秒
    private static Jedis jedis = new Jedis("localhost", 6379);

    public static void main(String[] args) {
        // 模拟缓存批量设置，且过期时间相同
        for (int i = 0; i < CACHE_SIZE; i++) {
            String key = "key_" + i;
            String value = "value_" + i;
            jedis.setex(key, EXPIRE_TIME, value);
        }

        // 模拟一段时间后缓存集中失效，请求直接访问数据库
        try {
            Thread.sleep((EXPIRE_TIME + 1) * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < CACHE_SIZE; i++) {
            String key = "key_" + i;
            String value = jedis.get(key);
            if (value == null) {
                // 缓存失效，从数据库获取数据
                value = getDataFromDatabase(key);
                // 重新设置缓存
                jedis.setex(key, EXPIRE_TIME, value);
            }
            System.out.println("Key: " + key + ", Value: " + value);
        }
        jedis.close();
    }

    private static String getDataFromDatabase(String key) {
        // 模拟从数据库获取数据
        return "db_" + key;
    }
}